package com.oocl.RTRLServer.parser.impl;

import java.io.IOException;

import com.oocl.RTRLServer.dao.UserDao;
import com.oocl.RTRLServer.dao.impl.UserDaoImpl;
import com.oocl.RTRLServer.manager.ServerManager;
import com.oocl.RTRLServer.parser.ProtocolParser;
import com.oocl.RTRLServer.pojo.User;
import com.oocl.RTRLServer.server.ServerThread;
import com.oocl.communicator.Sender;
import com.oocl.constant.Constant;
import com.oocl.constant.ProtocolType;
import com.oocl.pojo.Protocol;

public class ProtocolParserImpl implements ProtocolParser{
	private Sender sender;
	private UserDao userDao;
	
	public ProtocolParserImpl(Sender sender) {
		this.sender = sender;
		userDao = new UserDaoImpl();
	}

	@Override
	public void parseLogin(Protocol protocol, ServerThread userThread)
			throws IOException {
		String username = protocol.getFrom();
		if(null==username || username.equals("")){
			return;
		}
		User user = new User(null, username, protocol.getContent());
		String msg = chackUser(user);
		if(Constant.LOGIN_SUCCESS.equals(msg)){
			protocol.setType(ProtocolType.LOGIN_SUCCESS);
		}else {
			protocol.setType(ProtocolType.ERROR);
		}
		protocol.setContent(msg);
		sender.send(protocol);
		userThread.setRunning(false);
	}

	private String chackUser(User user) {
		User u = userDao.findUserByName(user.getUsername());
		System.out.println(u);
		if(null==u){
			return Constant.USERNAME_NOT_EXIST;
		}else {
			if(!u.getPassword().equals(user.getPassword())){
				return Constant.PASSWORD_ERROR;
			}else {
				return Constant.LOGIN_SUCCESS;
			}
		}
	}

	@Override
	public void parseRegister(Protocol protocol, ServerThread userThread)
			throws IOException {
		String username = protocol.getFrom();
		if(null==username || username.equals("")){
			return;
		}
		User user = userDao.findUserByName(username);
		System.out.println(user);
		if(user!=null){
			protocol.setType(ProtocolType.ERROR);
			protocol.setContent("user already exits!");
		}else {
			user = new User(null, username, protocol.getContent());
			int m = userDao.addUser(user);
			if(m==1){
				protocol.setType(ProtocolType.REGISTER_SUCCESS);
				protocol.setContent("Register success!");
			}else {
				protocol.setType(ProtocolType.ERROR);
				protocol.setContent("Register fail!");
			}
		}
		sender.send(protocol);
		userThread.setRunning(false);
	}


	@Override
	public void parseStopServer(Protocol protocol, ServerThread userThread)
			throws IOException {
//		ServerManager.stopServer();
//		userThread.setRunning(false);
	}
	
}
